package com.baosight.xCyber.util;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.baosight.xCyber.model.TagNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据数据库中存在的树结构和节点数据组装成树
 * @author wuqihang
 */
public class BuildTree {

    private static Logger logger = LoggerFactory.getLogger(BuildTree.class);
    private static Map<String, TagNode> treeTemp,mainTemp;
    private static String rootName;

    public static String initMap(Map<String,TagNode> main,
                                 Map<String,TagNode> tree){
        rootName="";
        mainTemp = main;
        treeTemp = tree;
        BuildTree buildTree = new BuildTree();
        buildTree.initMainNode();
        buildTree.addTreeNode();
        TagNode currnode = mainTemp.get(rootName);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        String[] filterList=new String[]{
                "showName",
                "itemFlag",
                "remarkName",
                "source",
                "serviceId",
                "unit",
                "parentId",
                "treeName",
                "desc",
                "extraParam",
                "lazyLoad",
                "attr",
                "orderNo"
        };
        Arrays.stream(filterList).forEach(filter.getExcludes()::add);

        logger.info(currnode.treeName+":过滤建立树成功");
        return JSONObject.toJSONString(currnode, filter);
    }


    private void initMainNode(){
        TagNode tagNode,parentTagNode;
        for(Map.Entry<String,TagNode> entry:mainTemp.entrySet()){
            tagNode = entry.getValue();

            String parentName = tagNode.parentId;
            if(tagNode.tagName.toLowerCase().contains("title")){
                tagNode.tagName=tagNode.showName;
            }

            //记录根节点的名称
            if(parentName.equals("")){
                rootName = entry.getKey();
                logger.info("{}:根节点名称:{}",tagNode.treeName,rootName);
                continue;
            }

            parentTagNode = mainTemp.get(parentName);
            parentTagNode.setItemFlag(true);
            List<TagNode> childs = parentTagNode.getItems();

            if(!childs.contains(tagNode)){
                childs.add(tagNode);
                parentTagNode.setItems(childs);
            }
        }
    }

    private void addTreeNode(){
        TagNode tagNode,parentMainNode;
        for(Map.Entry<String,TagNode> entry:treeTemp.entrySet()){
            tagNode = entry.getValue();
            tagNode.setItems(null);

            String parentName = tagNode.parentId.trim();
            parentMainNode = mainTemp.get(parentName);
            if(parentMainNode==null){
                continue;
            }
            parentMainNode.getItems().add(tagNode);
        }
    }
}
